import * as THREE from "three";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls";
import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader";
import { createGradientMaterial, createBackMaterial } from '../pages/index/js/jbs'
import { getPinkDetail } from '../api/glasses/index.js';
export default {
  data() {
    return {
      current: 0, //当前显示的图片
      scale: 0,
      controls: null, //控制器
      scene: null, //场景
      camera: null, //相机,
      modelAll: null, //模型
      modelOne: null, //模型
      modelTwo: null, //模型
      modelThree: null, //模型
      modelFour: null, //模型
      modelFive: null, //模型
      modelSix: null,  //镜片LOGO模型
      lensGroup: null,
      renderer: null, //渲染器
      frameMaterial: null, // 眼镜框架材质
      legMaterial: null, // 眼镜腿材质
      glassMaterial: null, // 眼镜镜片材质
      logoMaterial: null, // 眼镜框logo材质
      commonMaterial: null, // 公共材质
      list1: [
        "https://xxx.com/swiper/swiper1.png",
        "https://xxx.com/swiper/swiper2.png",
        "https://xxx.com/swiper/swiper3.png",
      ],
      isMoreColor: false,
      gradientMaterial: null,
      allObj: null,
      initialModelState: null
    };
  },
  onLoad: function (options) {
    this.getinitData('1')
  },
  methods: {
    getinitData(id) {
      getPinkDetail(id).then(res => {
        if (res.code == 200) {
          this.allObj = res.data
          console.log('res.data',res.data);
          
          this.submitObj.id=res.data.id
          this.$set(this.jkObj, 'type', 'glassesFrame');
          this.$set(this.jkObj, 'id', res.data.glassesFrame);
          this.$set(this.jkObj, 'explain', res.data.glassesFrameExplain);
          this.$set(this.jkObj, 'obj', res.data.glassesFrameList ? res.data.glassesFrameList[0] : null);
          this.submitObj.glassesFrame.name=res.data.glassesFrameList[0].detail[0].name
          this.submitObj.glassesFrame.value=res.data.glassesFrameList[0].detail[0].value
          this.$set(this.jtObj, 'type', 'glassesLeg');
          this.$set(this.jtObj, 'id', res.data.glassesLeg);
          this.$set(this.jtObj, 'explain', res.data.glassesLegExplain);
          this.$set(this.jtObj, 'obj', res.data.glassesLegList ? res.data.glassesLegList[0] : null);
          this.submitObj.glassesLeg.name=res.data.glassesFrameList[0].detail[0].name
          this.submitObj.glassesLeg.value=res.data.glassesFrameList[0].detail[0].value
          this.$set(this.jpObj, 'type', 'lensColor');
          this.$set(this.jpObj, 'id', '');
          this.$set(this.jpObj, 'explain', res.data.lensColorExplain);
          this.$set(this.jpObj, 'list', res.data.lensColor ? JSON.parse(res.data.lensColor) : null);
          this.submitObj.lensObj.name=JSON.parse(res.data.lensColor)[0].name
          this.submitObj.lensObj.value=JSON.parse(res.data.lensColor)[0].assistColors
          this.$set(this.gsObj, 'type', 'sportHang');
          this.$set(this.gsObj, 'id', res.data.sportHang);
          this.$set(this.gsObj, 'explain', res.data.sportHangExplain);
          this.$set(this.gsObj, 'obj', res.data.sportHangList ? res.data.sportHangList[0] : null);

          this.$set(this.bdObj, 'type', 'glassesBag');
          this.$set(this.bdObj, 'id', res.data.glassesBag);
          this.$set(this.bdObj, 'explain', res.data.glassesBagExplain);
          this.$set(this.bdObj, 'obj', res.data.glassesBagList ? res.data.glassesBagList[0] : null);

          this.$set(this.jhObj, 'type', 'glassesCase');
          this.$set(this.jhObj, 'id', res.data.glassesCase);
          this.$set(this.jhObj, 'explain', res.data.glassesCaseExplain);
          this.$set(this.jhObj, 'obj', res.data.glassesCaseList ? res.data.glassesCaseList[0] : null);
          if (res.data.lensLogoFrontList && res.data.lensLogoFrontList[0].detail) {
            this.ztList = res.data.lensLogoFrontList[0].detail.map(item => {
              return {
                pic: item.pic,
                text: item.name,
                value: item.value
              }
            })
            this.submitObj.logoText.fontFamily=res.data.lensLogoFrontList[0].detail[0].value
          }
          this.logoExplain = res.data.lensLogoExplain
          if (res.data.glassesFrameList) {
            this.frameMaterial = new THREE.MeshPhysicalMaterial({
              color: res.data.glassesFrameList[0].detail[0].value, // 假设使用深灰色，类似于砂色但更接近骑行眼镜框的颜色
              roughness: 0.4, // 调整粗糙度以更好地模拟塑料质感
              metalness: 0.2, // 增加金属度以增加反光效果
              transparent: false, // 禁用透明度
              opacity: 1, // 不透明
              envMapIntensity: 0.7, // 增加环境贴图强度以增强反光效果
              transmission: 0, // 关闭折射
              clearcoat: 0.1, // 增加清漆效果以模拟更光滑的表面
              clearcoatRoughness: 0.1,
              refractionRatio: 0, // 关闭折射率
            });
          }
          if (res.data.glassesLegList) {
            this.legMaterial = new THREE.MeshPhysicalMaterial({
              color: res.data.glassesLegList[0].detail[0].value, // 砂色
              roughness: 0.5, // 增加粗糙度以模拟塑料质感
              metalness: 0, // 金属度设为0以避免金属效果
              transparent: false, // 禁用透明度
              opacity: 1, // 不透明
              envMapIntensity: 0.5, // 减少环境贴图强度
              transmission: 0, // 关闭折射
              clearcoat: 0, // 清漆效果设为0
              clearcoatRoughness: 0,
              refractionRatio: 0, // 关闭折射率
            });
          }
          if (res.data.lensColor && JSON.parse(res.data.lensColor)[0].assistColors) {
            const colorList = JSON.parse(res.data.lensColor)[0].assistColors
            if (colorList.length) {
              this.isMoreColor = true
              this.gradientMaterial = createGradientMaterial(colorList)
            } else {
              const color = JSON.parse(res.data.lensColor)[0].mainColor
              this.glassMaterial = new THREE.MeshPhysicalMaterial({
                color: color, // 假设使用绿色，运动风格的颜色
                roughness: 0.3, // 增加粗糙度以减少透明度效果，但保持一定的透明感
                metalness: 0.1, // 增加金属度以增加反光效果
                transparent: true, // 启用透明度
                opacity: 0.8, // 设置透明度值，比原来的要高一些，以体现半透明效果
                envMapIntensity: 0.8, // 减少环境贴图强度，以控制反光效果
                transmission: 0.7, // 减少折射度，以减少光线衰减程度
                clearcoat: 0.1, // 增加清漆效果
                clearcoatRoughness: 0.1,
                refractionRatio: 1.3, // 减少折射率，以控制光的折射程度
              });
            }
          }
          // if (res.data.sportHangList) {
          //   this.gsImgUrl = res.data.sportHangList[0].detail[0].pic
          // }
          // if (res.data.glassesBagList) {
          //   this.bdImgUrl = res.data.glassesBagList[0].detail[0].pic
          // }
          // if (res.data.glassesCaseList) {
          //   this.jhImgUrl = res.data.glassesCaseList[0].detail[0].pic
          // }
          this.initThree(res.data.modelUrl)
        } else {
          uni.showToast({
            title: '获取眼镜数据错误',
            icon: 'none',
            duration: 2000
          });
        }
      })
    },
    initThree(modelUrl) {
      let that = this;
      // 创建场景
      this.scene = new THREE.Scene();
      // 创建相机
      that.camera = new THREE.PerspectiveCamera(
        45,
        window.innerWidth / window.innerHeight,
        0.1,
        1000
      );
      // 调整相机位置
      that.camera.position.set(0, 0.5, 1.6); // Y轴位置上移
      that.camera.lookAt(0, 0.5, 0); // 注视点上移
      // 创建渲染器
      that.renderer = new THREE.WebGLRenderer({
        // 开启抗锯齿
        antialias: true,
        alpha: true,
        precision: 'highp',
        powerPreference: "high-performance"
      });
      that.renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2))
      // 设置渲染器大小
      that.renderer.setSize(window.innerWidth, window.innerHeight);
      // 将渲染器的dom添加到页面中
      this.$refs.canvasRef.appendChild(that.renderer.domElement);
      // 设置背景色
      that.renderer.setClearColor(0x000000, 0);
      this.scene.background = new THREE.Color("#fff");
      // this.scene.background = null;
      this.scene.environment = new THREE.Color("#fff");
      // 开始渲染
      const animate = function () {
        requestAnimationFrame(animate);
        that.renderer.render(that.scene, that.camera);
        that.controls && that.controls.update();
      };
      animate();
      // 添加网格地面
      //添加控制器
      this.controls = new OrbitControls(that.camera, that.renderer.domElement);
      this.controls.minPolarAngle = Math.PI / 2.5;  // 限制垂直旋转最小值（90度）
      this.controls.maxPolarAngle = Math.PI / 2.5;  // 限制垂直旋转最大值（90度）
      this.controls.enableZoom = false;
      this.controls.enablePan = false;
      this.controls.update();
      // 创建材质
      this.commonMaterial = new THREE.MeshPhysicalMaterial({
        color: 0x000000, // 黑色
        roughness: 0.8, // 较高的粗糙度以模拟橡胶质感
        metalness: 0, // 金属度设为0以避免金属效果
        clearcoat: 0, // 清漆效果设为0
        clearcoatRoughness: 0,
        transparent: true, // 启用透明度
        opacity: 0.9, // 设置透明度值，接近不透明
        envMapIntensity: 0.2, // 减少环境贴图强度
      });
      this.logoMaterial = new THREE.MeshPhysicalMaterial({
        color: 0x6bd6d6,
        roughness: 0.5,
        metalness: 1,
        clearcoat: 1,
        clearcoatRoughness: 0,
      });
      // 加载模型
      this.loadModel(modelUrl);
    },
    // 加载模型
    async loadModel(modelUrl) {
      let that = this;
      const loader = new GLTFLoader();
      const backMaterial = createBackMaterial();
      loader.load(
        // 资源路径
        "/static/model/snap-ar-glasses-2022.gltf",
        // modelUrl,
        // 加载完成后的回调函数
        function (gltf) {
          that.modelAll = gltf.scene;
          // 保存初始状态
          that.modelAll.traverse(function (child) {
            if (child.isMesh && child.name === "镜片_1") {
              const geometry = child.geometry.clone();
              geometry.scale(-1, 1, -1);
              const backMesh = new THREE.Mesh(geometry, backMaterial);
              backMesh.position.set(0, 0, -0.0000015)
              backMesh.rotation.y = Math.PI; // Rotate 180 degrees to flip the back
              child.add(backMesh);

              // Apply gradient material to the front
              // child.material = gradientMaterial;
              that.modelOne = child;
              if (that.isMoreColor) {
                that.modelOne.material = that.gradientMaterial;
              } else {
                that.modelOne.material = that.glassMaterial;
              }
            }
            if (child.isMesh && child.name === "上镜框") {
              that.modelTwo = child;
              that.modelTwo.material = that.frameMaterial;
            }
            if (child.isMesh && child.name === "下镜框") {
              that.modelTwo = child;
              that.modelTwo.material = that.frameMaterial;
            }
            if (child.isMesh && child.name === "鼻托_1") {
              that.modelThree = child;
              that.modelThree.material = that.commonMaterial;
            }
            if (child.isMesh && child.name === "左镜腿_1") {
              that.modelFour = child;
              that.modelFour.material = that.legMaterial;
            }
            if (child.isMesh && child.name === "右镜腿_1") {
              that.modelFour = child;
              that.modelFour.material = that.legMaterial;
            }
            if (child.isMesh && child.name === "右腿套") {
              that.modelThree = child;
              that.modelThree.material = that.commonMaterial;
            }
            if (child.isMesh && child.name === "左腿套") {
              that.modelThree = child;
              that.modelThree.material = that.commonMaterial;
            }
            if (child.isMesh && child.name === "左镜腿logo") {
              that.modelFive = child;
              that.modelFive.material = that.logoMaterial;
            }
            if (child.isMesh && child.name === "右镜腿logo") {
              that.modelFive = child;
              that.modelFive.material = that.logoMaterial;
            }
            if (child.isMesh && child.name === '镜片LOGO') {
              child.parent.remove(child);
            }
          });
          const box = new THREE.Box3().setFromObject(that.modelAll);
          const center = box.getCenter(new THREE.Vector3());
          that.modelAll.position.sub(center);
          that.modelAll.position.y = 0.4;
          const size = box.getSize(new THREE.Vector3());
          const maxDim = Math.max(size.x, size.y, size.z);
          const scale = 0.6 / maxDim;
          that.modelAll.scale.multiplyScalar(scale);
          that.scene.add(that.modelAll);
          that.addDirectionalLight()
          that.initialModelState = {
            position: new THREE.Vector3().copy(that.modelAll.position),
            rotation: new THREE.Euler().copy(that.modelAll.rotation),
            scale: new THREE.Vector3().copy(that.modelAll.scale)
          };
        },
        // 加载过程中的回调函数
        function (xhr) {
          console.log((xhr.loaded / xhr.total) * 100 + "% loaded");
          that.loadText = '加载中' + Math.floor((xhr.loaded / xhr.total) * 100) + "%"
          if (((xhr.loaded / xhr.total) * 100) === 100) {
            that.loading = false
          }
        },
        // 加载出错的回调函数
        function (error) {
          console.error(error);
        }
      );
    },
    SwiperChange(e) {
      this.current = e.detail.current;
    },

    //rpx转px
    rpxToPx(rpx) {
      const screenWidth = uni.getSystemInfoSync().screenWidth;
      return (screenWidth * Number.parseInt(rpx)) / 750;
    },
    leftEvent() {
      if (this.current > 0) {
        this.current--;
      } else {
        this.current = 3;
      }
    },
    rightEvent() {
      if (this.current < this.list1.length - 1) {
        this.current++;
      } else {
        this.current = 0;
      }
    },
    // 眼镜片表面渲染文字或图片
    createLogoTexture(input, isImage = false) {
      return new Promise((resolve, reject) => {
        const canvas = document.createElement('canvas');
        const ctx = canvas.getContext('2d');
        canvas.width = 512;
        canvas.height = 512;

        ctx.fillStyle = 'rgba(0, 0, 0, 0)';
        ctx.fillRect(0, 0, canvas.width, canvas.height);

        if (isImage) {
          const img = new Image();
          img.crossOrigin = 'anonymous';
          img.src = input;
          img.onload = () => {
            // 计算缩放比例
            const scale = Math.min(canvas.width / img.width, canvas.height / img.height) * 0.2; // 0.8 是为了留一些边距
            const newWidth = img.width * scale;
            const newHeight = img.height * scale;

            // 计算居中位置
            const x = (canvas.width - newWidth) / 2;
            const y = (canvas.height - newHeight) / 2;

            // 清除画布
            ctx.clearRect(0, 0, canvas.width, canvas.height);

            // 绘制缩小并居中的图片
            ctx.drawImage(img, x, y, newWidth, newHeight);

            const texture = new THREE.CanvasTexture(canvas);
            texture.needsUpdate = true;
            resolve(texture);
          };
          img.onerror = () => {
            reject(new Error('图片加载失败'));
          };
        } else {
          ctx.font = '20px';
          ctx.fillStyle = 'white';
          ctx.textAlign = 'center';
          ctx.textBaseline = 'middle';
          ctx.fillText(input, canvas.width / 2, canvas.height / 2);

          const texture = new THREE.CanvasTexture(canvas);
          texture.needsUpdate = true;
          resolve(texture);
        }
      });
    },
    // 添加定向光
    addDirectionalLight() {
      // 添加定向光
      var directionalLight0 = new THREE.DirectionalLight(0xffffff, 1); // 颜色和强度
      directionalLight0.position.set(1, 1, 1); // 光源位置
      this.scene.add(directionalLight0);

      var directionalLight1 = new THREE.DirectionalLight(0xffffff, 1); // 颜色和强度
      directionalLight1.position.set(-1, 1, 1); // 光源位置
      this.scene.add(directionalLight1);

      var directionalLight2 = new THREE.DirectionalLight(0xffffff, 1); // 颜色和强度
      directionalLight2.position.set(-1, 1, -1); // 光源位置
      this.scene.add(directionalLight2);

      var directionalLight3 = new THREE.DirectionalLight(0xffffff, 1); // 颜色和强度
      directionalLight3.position.set(1, 1, -1); // 光源位置
      this.scene.add(directionalLight3);

      var directionalLight4 = new THREE.DirectionalLight(0xffffff, 1); // 颜色和强度
      directionalLight4.position.set(1, -1, 1); // 光源位置
      this.scene.add(directionalLight4);

      var directionalLight5 = new THREE.DirectionalLight(0xffffff, 1); // 颜色和强度
      directionalLight5.position.set(-1, -1, 1); // 光源位置
      this.scene.add(directionalLight5);

      var directionalLight6 = new THREE.DirectionalLight(0xffffff, 1); // 颜色和强度
      directionalLight6.position.set(1, -1, -1); // 光源位置
      this.scene.add(directionalLight6);

      var directionalLight7 = new THREE.DirectionalLight(0xffffff, 1); // 颜色和强度
      directionalLight7.position.set(-1, -1, -1); // 光源位置
      this.scene.add(directionalLight7);
    },
  }
};